package cn.yx.framework.configuration;


import cn.com.yx.ms.domain.mq.MqConfigQueueModel;
import cn.com.yx.ms.service.IMqService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZHUL
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2017-02-13 8:14
 */
//@Import(RabbitMQConfig.class)
//@Configuration
public class AmqpConfig {
    private static final Logger logger = LoggerFactory.getLogger(BaseConstant.class);
    //public static final String EXCHANGE = "spring-boot-exchange";
    public static final String ROUTINGKEY = "spring-boot-routingKey";

    @Resource
    RabbitMQConfig rabbitMQConfig;

    @Resource
    IMqService iMqService;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(rabbitMQConfig.rabbitMqServer().getAddress());
        connectionFactory.setUsername(rabbitMQConfig.rabbitMqServer().getUsername());
        connectionFactory.setPassword(rabbitMQConfig.rabbitMqServer().getPassword());
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true); //必须要设置

        return connectionFactory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    /**
     * 针对消费者配置
     * 1. 设置交换机类型
     * 2. 将队列绑定到交换机
     * <p>
     * <p>
     * FanoutExchange: 将消息分发到所有的绑定队列，无routingkey的概念
     * HeadersExchange ：通过添加属性key-value匹配
     * DirectExchange:按照routingkey分发到指定队列
     * TopicExchange:多关键字匹配
     */
//    @Bean
//    public DirectExchange defaultExchange() {
//        return new DirectExchange(EXCHANGE, false, false);
//    }
    @Bean
    public String getTopicExchangeName() {
        return rabbitMQConfig.exchangeConfig().getName();
    }

    @Bean
    public TopicExchange topicExchange() {
        //return new TopicExchange(EXCHANGE, false, false);
        return new TopicExchange(rabbitMQConfig.exchangeConfig().getName(), rabbitMQConfig.exchangeConfig().getDurable(), false);
    }

//    /**
//     * spring-boot-queue
//     *
//     * @return
//     */
//
//    @Bean
//    public Queue queue() {
//        return new Queue("spring-boot-queue-1", false); //队列持久
//    }
//
//    @Bean
//    public Queue queue2() {
//        return new Queue("spring-boot-queue-2", false); //队列持久
//    }
//
//    @Bean
//    public Queue queue3() {
//        return new Queue("spring-boot-queue-3", false); //队列持久
//    }

//    @Bean
//    public Binding binding() {
//
//         return BindingBuilder.bind(queue()).to(topicExchange()).with(AmqpConfig.ROUTINGKEY);
//
//    }
//
//    @Bean
//    public Binding binding2() {
//        return BindingBuilder.bind(queue2()).to(topicExchange()).with("spring-boot-routingKey-2");
//    }


    @Bean
    public List<Binding> bindings() {
        List<MqConfigQueueModel> mqConfigQueueModels = iMqService.GetMqConfigQueues();
        List<Binding> bindings = new ArrayList<>();
        for (MqConfigQueueModel mqConfigQueueModel : mqConfigQueueModels) {
            Queue queue = new Queue(mqConfigQueueModel.getQueue(), false);
            bindings.add(BindingBuilder.bind(queue)
                    .to(topicExchange())
                    .with(mqConfigQueueModel.getRoutingkey()));
        }

        return bindings;
    }


    @Bean
    public SimpleMessageListenerContainer messageContainer1() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());

        List<Queue> queues = new ArrayList<>();
        for (MqConfigQueueModel mqConfigQueueModel : iMqService.GetMqConfigQueues()) {
            if (mqConfigQueueModel.getQueue().contains(".up")) {
                queues.add(new Queue(mqConfigQueueModel.getQueue(), false));
            }
        }
        Queue[] arrQueue = queues.toArray(new Queue[queues.size()]);
        container.setQueues(arrQueue);
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(500);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                System.out.println("receive msg 1: " + new String(body) + ",channel : " + message.getMessageProperties().getConsumerQueue());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                logger.debug("MQ接收数据开始...");

                //MyLogger.log("", "");
                try {
                    iMqService.receive(new String(body));

                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                    for (StackTraceElement stack :
                            ex.getStackTrace()) {
                        logger.error(stack.getClassName() + "|" + stack.getFileName() + "|" + stack.getMethodName() + "|" + stack.getLineNumber());
                    }
                } finally {
                    //MyLogger.log("", "");
                    logger.debug("MQ接收数据结束...");
                }
            }
        });
        return container;
    }


}

